/**
 * Created by udi on 2016/11/30.
 */

'use strict'

let mor = require("../libs/mongo/mongoHelper");
let querystring = require('querystring');
let dbr = require("../libs/mysql/mysqlHelper");
let jv = require("../libs/sys/myHelper").jv;
let request = require('request');
let fs = require("fs");


app.use(app.routes.get('/img', async function (ctx) {
  var params = querystring.parse(ctx.req._parsedUrl.query);
  let url = app.appConfig.imageHost + params.url;

  // request(app.appConfig.imageHost + url)
  //   .pipe(ctx.res);

  // ctx.set("Content-Type", "image/png");

  let other = await new Promise(function (accept, reject) {

    return request.get(url, function (err, response, data) {
      if (err) {
        accept(null);
        return ;
      }
      accept(response);

      // ctx.status = response.statusCode;
      // for (var h in response.headers) {
      //   ctx.set(h, response.headers[h]);
      // }
    }).on("data", o => {

      ctx.res.write(o);
    }).on("response", response => {
      ctx.status = response.statusCode;
      for (var h in response.headers) {
        ctx.set(h, response.headers[h]);
      }
    });
  })

  if (!other) {
    return;
  }


  //fs.createReadStream(other).pipe(ctx.response);

  // other.pipe(ctx.res);


  // other.res.pipe(ctx.res);

  // ctx.res.write(other.body);
  // ctx.res.set( other.headers)
}));
